var util = require('../../libs/util.js');
var moment = require('../../libs/moment.min.js');
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    pageSize: 10,
    pageNumber: 0,
    count: 0,
    page: 1,
    firstPage: true,
    prevPage: true,
    nextPage: true,
    lastPage: true,
    fee_month:moment().format('YYYY-MM-DD'),
    imgList:[],
    formType : 'add'
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    wx.setNavigationBarTitle({ "title": "车辆档案" });
    var that = this;
    //更新数据
    that.setData({
      vehicle_id: e.id,
      tab: e.tab || 4,
      role_default:app.globalData.role_default,
      server:app.server
    });
    if(e.path_name){
      that.setData({
        path_name: e.path_name
      });
    }
    if(e.delivery){
      that.setData({
        delivery: e.delivery,
        modalName:'detailModal',
        modalTitle:'新增停车费用',
        modalType:'add'
      });
    }
    this.loadData();
  },
  bindInput: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  search: function () {
    this.loadData();
  },
  chooseLocation:function(e){
    var that = this;
    wx.chooseLocation({
      success(res) {
        console.log(res)
        that.setData({
          place: String(res.address).replace("'","")
        });
      }
    })
  },
  chooseDelivery:function(e){
    var that = this;
    wx.navigateTo({
      url: '/pages/schedule/delivery_select?vehicle='+that.data.vehicle_id
    })
  },
  deleteDelivery:function(e){
    var that = this;
    that.setData({
      delivery:'',
      path_name:''
    })
    wx.showToast({
      title: "已清除关联运单",
      icon: "success",
      duration: 3000,
      success: function () {

      }
    });
  },
  loadData: function () {
    var that = this;
    wx.showLoading({
      title: '请稍候...',
    });
    util.postData("/zhc/datalist/getDataByListId",{
      "list_id": "7526948E-A55B-4CA4-B588-FC37B82443A7",
      "res": "",
      "page": {
        "size": 20,
        "current": 1,
        "orders": [
          {
            "column": "a.ADD_TIME",
            "asc": "false"
          }
        ]
      },
      "data": {
        "field": ""
      },
      "repeat_field": [],
      "condition": " a.CO_ID='"+app.globalData.CO_ID+"' and  a.BE_DEL=0 ",
      "virtual_field": []
    }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (error) {
        return false;
      }
      if (res.data.success && res.data?.result?.records.length > 0) {
        var count = res.data.result.total;
        var pageNumber = Math.ceil(count / that.data.pageSize);
        wx.setNavigationBarTitle({ "title": "车辆停车费--" + res.data.result.records[0].plate });
          that.setData({
            plate:res.data.result.records[0].plate,
            d_user_id:res.data.result.records[0].d_user_id,
            user_id:app.globalData.user_id,
            is_fleet:app.globalData.role_default == 'fleet'?true:false,
            dataList: res.data.result.records,
            count: count,
            pageNumber: pageNumber,
            page: that.data.page == 0 ? 1 : that.data.page
          });
          that.setPageStatus();
        } else {
          that.setData({
            page: 0,
            dataList: []
          });
        }
    });
  },
  //翻页按钮状态
  setPageStatus: function () {
    var that = this;
    var page = that.data.page, pageNumber = that.data.pageNumber;
    if (pageNumber == 1) {
      that.setData({
        firstPage: true,
        prevPage: true,
        nextPage: true,
        lastPage: true
      });
    } else if (pageNumber > 1) {
      if (page == 1) {
        that.setData({
          firstPage: true,
          prevPage: true,
          nextPage: false,
          lastPage: false
        });
      } else if (page == pageNumber) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: true,
          lastPage: true
        });
      } else if (page < pageNumber && page > 1) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: false,
          lastPage: false
        });
      }
    }
  },
  //分页按钮操作
  pageChange: function (e) {
    var type = e.currentTarget.dataset.page;
    if (type == 'first') {
      this.setData({
        page: 1
      })
      this.loadData();
    }
    if (type == 'last') {
      this.setData({
        page: this.data.pageNumber
      })
      this.loadData();
    }
    if (type == 'prev') {
      this.setData({
        page: this.data.page - 1
      })
      this.loadData();
    }
    if (type == 'next') {
      this.setData({
        page: this.data.page + 1
      })
      this.loadData();
    }
  },
  showModal(e) {
    var that = this;
    this.setData({
      modalName: e.currentTarget.dataset.target,
      modalTitle: e.currentTarget.dataset.title,
      modalType:e.currentTarget.dataset.type
    })
    if(e.currentTarget.dataset.type == 'detail'){
       var id = e.currentTarget.id;
       var dataList = that.data.dataList;
       for(var i=0;i<dataList.length;i++){
         if(dataList[i].ID == id){
           var currentData = [];
           currentData.push({name:'停车费',value:dataList[i].fee});
           currentData.push({name:'费用日期',value:dataList[i].fee_month});
           currentData.push({name:'关联运单',value:dataList[i].path_name});
           currentData.push({name:'图片单据',value:dataList[i].documents?String(dataList[i].documents).split(','):[]});
            that.setData({
              _currentData:dataList[i],
               currentData:currentData
            })
         }
       }
    }
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  showPictrue: function (e) {
    var image = e.currentTarget.dataset.image;
    wx.previewImage({
      urls: image
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.dataset.url, // 当前显示图片的http链接
      urls: [e.currentTarget.dataset.url] // 需要预览的图片http链接列表
    })
  },
  chooseImage: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.name;
    var imgList = that.data.imgList;
    try{
      var formData = {
        'id': that.data.vehicle_id,
        'type':'tollfee'
      };
    }catch(e){}
    wx.chooseMedia({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res)
        wx.showLoading({
          title: '上传中...'
        });
        wx.uploadFile({
          url: app.server +'/commons/file/uploads',
          header:{
            'Authorization': app.globalData.token
          },
            filePath: res.tempFiles[0].tempFilePath,
            name: 'file',
            formData: formData,
            success: function (res) {
              var data = JSON.parse(res.data); console.log(data)
              if (data.success) {
                imgList.push(data.result[0]);
                imgList = util.arrayDeleteEmpty(imgList);
                that.setData({
                  imgList: imgList
                });
              }else{
                wx.showToast({
                  title: "上传失败",
                  image: '/images/wrong.png',
                  duration: 2000
                });
              }
            },
            complete: function () {
              wx.hideLoading();
            }
          })
      }
    })
  },
  DelImg: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    console.log(index)
    var type = e.currentTarget.dataset.name;
    console.log(type)
    var imgList = that.data.imgList;
    var url = imgList[index];
    wx.showModal({
      title: '温馨提示',
      content: '确定要删除图片吗？',
      success (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...'
          });
          if(url == ''){
            if (imgList.length == 1) {
              imgList = [];
            } else {
              imgList.splice(index, 1);
            }
            that.setData({
              imgList: imgList
            })
            wx.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 2000,
              success: function () {

              }
            });
            return false;
          }
          util.putData("/atapi/vehicle/vehicle/deleteFile", {
            url: url
          }, function (res, error) {
            console.log(res); console.log(error)
            wx.hideLoading();
            if (error) {
              wx.showToast({ title: '删除失败', image: '/images/wrong.svg', duration: 2000 });
              return false;
            }
            if (res.data.success) {
              if (imgList.length == 1) {
                imgList = [];
              } else {
                imgList = util.arrayDeleteWithIndex(imgList, index,1);
              }
              that.setData({
                imgList: imgList
              })
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000,
                success: function () {
                  
                }
              });
            }
          });
        }
      }
    });
  },
  chooseFile: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.name;
    var imgList = that.data.imgList;
    try{
      var formData = {
        'id': that.data.vehicle_id,
        'type':'tollfee'
      };
    }catch(e){}
    wx.chooseMessageFile({
      count: 1,
      type: 'all',
      success (res) {
        console.log(res)
        wx.showLoading({
          title: '上传中...'
        });
        wx.uploadFile({
          url: app.server +'/atapi/vehicle/vehicle/uploadImage',
          header:{
            'Authorization': app.globalData.token
          },
            filePath: res.tempFiles[0].path,
            name: 'file',
            formData: formData,
            success: function (res) {
              var data = JSON.parse(res.data); console.log(data)
              if (data.success) {
                that.setData({
                  tollfee_file: data.data
                });
              }else{
                wx.showToast({
                  title: "上传失败",
                  image: '/images/wrong.png',
                  duration: 2000
                });
              }
            },
            complete: function () {
              wx.hideLoading();
            }
          })
      }
    })
  },
  openFile:function(e){
    var that = this;
    var file = e.currentTarget.dataset.file;
    wx.downloadFile({
      // 示例 url，并非真实存在
      url: that.data.server + file,
      success: function (res) {
        const filePath = res.tempFilePath
        wx.openDocument({
          filePath: filePath,
          success: function (res) {
            console.log('打开文档成功')
          }
        })
      }
    })
  },
  deleteFile:function(e){
    var that = this;
    var file = e.currentTarget.dataset.file;
    wx.showLoading({
      title: '删除中...'
    });
    util.putData("/atapi/vehicle/vehicle/deleteFile", {
      url: file
    }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({ title: '删除失败', image: '/images/wrong.svg', duration: 2000 });
        return false;
      }
      if (res.data.success) {
        that.setData({
          tollfee_file: ""
        })
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            
          }
        });
      }
    });
  },
  //提交表单
  saveFormData: function () {
    var that = this;

    var formData = {};

    formData.delivery = that.data.delivery||'';
    formData.path_name = that.data.path_name||'';
    formData.fee = that.data.fee||'';
    formData.documents = that.data.imgList.join(",");
    formData.fee_month = that.data.fee_month||'';
    console.log(formData)
    if (formData.fee == '') {
      wx.showToast({
        title: "请填写费用",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (isNaN(formData.fee) == true) {
      wx.showToast({
        title: "费用错误",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (formData.fee_month == '') {
      wx.showToast({
        title: "请选择日期",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (formData.documents == '') {
      wx.showToast({
        title: "请上传单据",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    formData.vehicle = that.data.vehicle_id;
    formData.CO_ID = app.globalData.CO_ID;
    formData.plate = app.globalData.plate;
    util.postData("/sys/form/commonInsert",{
      "formId":"DCA2ADAB-1D91-4AF9-A6E0-D528AEE50968",
      "data":[formData],
      "condition":""
      }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (error) {
        return false;
      }
      if (res.data.success) {
        wx.showToast({
          title: "提交成功",
          icon: "success",
          duration: 3000,
          success: function () {
            setTimeout(function () {
              that.hideModal();
              that.loadData();
            }, 3000);
          }
        });
      } else {
        wx.showToast({
          title: "提交失败",
          image: '/images/wrong.png',
          duration: 3000
        });
      }
    });
  },
  deleteData:function(){
    var that = this;
    var _currentData = that.data._currentData;
    wx.showModal({
      title: '温馨提示',
      content: '确定要删除吗？',
      success (res) {
        if (res.confirm) {
            util.deleteData("/atapi/vehicle/vehicle/parkingfee", {
              id: _currentData.ID,
              user_id:app.globalData.user_id,
              CO_ID:app.globalData.CO_ID,
              truename:app.globalData.truename,
              logs:that.data.plate+','+_currentData.name+','+_currentData.site+','+_currentData.fee+','+_currentData.upkeep_time
            }, function (res, error) {
              console.log(res); console.log(error)
              wx.hideLoading();
              if (error) {
                wx.showToast({ title: '删除失败', image: '/images/wrong.svg', duration: 2000 });
                return false;
              }
              if (res.data.success) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 2000,
                  success: function () {
                    setTimeout(function(){
                      that.hideModal();
                        that.loadData();
                    },3000)
                  }
                });
              }
            });
          }
        }
        })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'deliverySelected',
      success(res) {
        if (res.data) {
          var data = res.data;
          that.setData({
            delivery: data.ID,
            path_name: data.path_name
          })
          wx.removeStorage({
            key: 'deliverySelected',
            success: function (res) {
            }
          });
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})